
<template lang="pug">
  .m-ratio(ref="ratio")
    .ratio-main(@mouseenter="enter($event)" @mouseleave="leave($event)")
      .ratio-item( v-for="(item,index) in itemClass" :style="item" :key="index") {{ratios[index]}}
</template>

<script>
import Vue from 'vue'
import { curry, isInstance } from '@/utils/index.js'

const descArr = '成功 在途 失败'.split(' ')
export default {
  props: {
    ratios: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      descArr,
      instance: ''
    }
  },
  computed: {
    itemClass () {
      let total = this.ratios.reduce((a, b) => a + b, 0)
      let _styleObj = curry(this.styleObj)(total)
      return this.ratios.map(d => _styleObj(d))
    }
  },
  mounted () {
    this.initpopover()
  },
  methods: {
    styleObj (total, val) {
      if (total) {
        return {
          width: val / total * 100 + '%'
        }
      }
    },
    initpopover () {
      let descArr = this.descArr
      const ratio = {
        render () {
          return (
            <div class='ratio-popover' v-show={this.visable} style={this.styleObject}>
              {descArr.map((d, i) => <div><i/><span>{d}</span>{this.ratioArr[i]}</div>)}
            </div>
          )
        },
        data () {
          return {
            visable: false,
            ratioArr: [0, 0, 0],
            styleObject: {
              top: 0,
              left: 0
            }
          }
        },
        methods: {
          setPosition (top, left, arr) {
            this.styleObject.top = top + 'px'
            this.styleObject.left = left + 'px'
            this.ratioArr = arr
          }
        }
      }
      const ratioConstructor = Vue.extend(ratio)
      this.instance = isInstance('ratio', new ratioConstructor().$mount())
    },
    enter (e) {
      let { left, top, width } = this.$refs.ratio.getBoundingClientRect()
      this.instance.visable = true
      this.instance.setPosition(top - 18, left + width - 6, this.ratios)
    },
    leave (e) {
      this.instance.visable = false
    }
  }
}
</script>
<style lang="stylus" scoped>
.m-ratio
  width 100%
  position relative
  z-index 1
  .ratio-item
    height 15px
    display inline-block
    border-right 1px solid #fff
    font-szie 12px
    line-height @height
    text-align center
    color #fff
    cursor pointer
    &:nth-child(1)
      background-color #a4d47d
    &:nth-child(2)
      background-color #90dbfe
    &:nth-child(3)
      background-color #f48f7a
    &:last-child
      border-right 0

</style>
